[...callback].ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import { redirect } from "@solidjs/router"
  2. import type { APIEvent } from "@solidjs/start/server"
  3. import { AuthClient } from "~/context/auth"
  4. import { useAuthSession } from "~/context/auth"
  5. import { fromPathname, localeFromRequest, route } from "~/lib/language"
  6. export async function GET(input: APIEvent) {
  7. const url = new URL(input.request.url)
  8. const locale = localeFromRequest(input.request)
  9. try {
  10. const code = url.searchParams.get("code")
  11. if (!code) throw new Error("No code found")
  12. const result = await AuthClient.exchange(code, `${url.origin}${url.pathname}`)
  13. if (result.err) throw new Error(result.err.message)
  14. const decoded = AuthClient.decode(result.tokens.access, {} as any)
  15. if (decoded.err) throw new Error(decoded.err.message)
  16. const session = await useAuthSession()
  17. const id = decoded.subject.properties.accountID
  18. await session.update((value) => {
  19. return {
  20. ...value,
  21. account: {
  22. ...value.account,
  23. [id]: {
  24. id,
  25. email: decoded.subject.properties.email,
  26. },
  27. },
  28. current: id,
  29. }
  30. })
  31. const next = url.pathname === "/auth/callback" ? "/auth" : url.pathname.replace("/auth/callback", "")
  32. if (fromPathname(next)) return redirect(next)
  33. return redirect(route(locale, next))
  34. } catch (e: any) {
  35. return new Response(
  36. JSON.stringify({
  37. error: e.message,
  38. cause: Object.fromEntries(url.searchParams.entries()),
  39. }),
  40. { status: 500 },
  41. )
  42. }
  43. }